package com.yunjian.core.admin;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yunjian.common.utils.*;
import com.yunjian.core.entity.*;
import com.yunjian.core.service.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.text.MessageFormat;
import java.util.*;

/**
 * <p>
 * 采购订单信息表 前端控制器
 * </p>
 *
 * @author xiapengyu
 * @since 2020-02-18
 */
@RestController
@RequestMapping("/sys/purchaseOrder")
public class SysPurchaseOrderController {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private IPurchaseOrderService purchaseOrderService;
    @Autowired
    private IPurchaseDetailService purchaseDetailService;
    @Autowired
    private IAccountService accountService;
    @Autowired
    private IMessageCenterService messageCenterService;
    @Autowired
    private JPushService jPushServiceImpl;

    /**
     * 分页查询采购单列表
     */
    @PostMapping("/list")
    public R queryOrderByPage(@RequestBody Map<String, Object> params) {
        logger.info("分页查询app用户采购单列表{}", JsonUtil.toJsonString(params));
        SysUserEntity user = (SysUserEntity) HttpContextUtils.getLoginUser().get("sysUser");

        //判断是否为经销商
        SysRoleEntity role = (SysRoleEntity) HttpContextUtils.getLoginUser().get("role");
        if (role != null && role.getRoleId().intValue() != Constant.SUPER_DEALER
                && role.getRoleId().intValue() != Constant.SUPER_ADMIN) {
            params.put("dealerId", user.getUserId());
        }
        PageUtils page = purchaseOrderService.queryOrderByPage4Sys(params);
        return R.ok().put("page", page);
    }

    /**
     * 分页查询采购单列表
     */
    @PostMapping("/delete")
    public R delete(@RequestBody Map<String, Object> params) {
        int id = (int) params.get("id");
        purchaseOrderService.removeById(id);
        return R.ok();
    }

    /**
     * 查看采购单详情
     */
    @PostMapping("/detail")
    public R detail(@RequestBody Map<String, Object> params) {
        R r = purchaseDetailService.queryPurchaseDetailInfo(params);
        return r;
    }

    @PostMapping("/queryDetail")
    public R queryDetail(@RequestBody Map<String, Object> params) {
        String id = StringUtil.obj2String(params.get("id"));
        PurchaseOrder order = purchaseOrderService.getOne(new QueryWrapper<PurchaseOrder>()
                .eq("id", Integer.parseInt(id)));

        List<PurchaseDetail> detailList = purchaseDetailService.list(new QueryWrapper<PurchaseDetail>()
                .eq("order_no", order.getOrderNo()));

        BigDecimal totalPrice = BigDecimal.ZERO;
        for(PurchaseDetail item : detailList){
            totalPrice = totalPrice.add(item.getPrice());
        }

        return R.ok().put("order", order).put("detailList", detailList).put("totalPrice", totalPrice);
    }

    /**
     * 修改经销商采购订单状态
     */
    @PostMapping("/updateOrderStatus")
    public R updateOrderStatus(@RequestBody Map<String, Object> params){
        logger.info("提交经销商采购订单{}", JsonUtil.toJsonString(params));
        String orderId = StringUtil.obj2String(params.get("orderId"));
        String status = StringUtil.obj2String(params.get("status"));
        PurchaseOrder order = purchaseOrderService.getOne(new QueryWrapper<PurchaseOrder>()
                .eq("id", Integer.parseInt(orderId)));

        SysUserEntity loginUser = HttpContextUtils.getLoginSysUserEntity();
        if (order.getDealerId().intValue() != loginUser.getUserId().intValue()){
            return R.error("无法操作他人采购单");
        }

        order.setStatus(Integer.parseInt(status));
        purchaseOrderService.saveOrUpdate(order);

        if(Integer.parseInt(status) == 3){
            Account account = accountService.getOne(new QueryWrapper<Account>()
                    .eq("id", order.getAccountId()));

            //极光推送发货消息给用户
            String title = LanguageUtils.getValueByKey("ship.notice");
            String pushMsg = LanguageUtils.getValueByKey("ship.msg");
            pushMsg = MessageFormat.format(pushMsg,order.getOrderNo(), DateUtils.format(new Date(), DateUtils.DATE_TIME_PATTERN_V));
            MessageCenter msg = new MessageCenter();
            msg.setAccountEmail(account.getEmail());
            msg.setAccountId(account.getId());
            msg.setContent(pushMsg);
            msg.setTitle(title);
            msg.setCreateTime(new Date());
            SysUserEntity sysUserEntity = HttpContextUtils.getLoginSysUserEntity();
            msg.setCreatorId(sysUserEntity.getUserId());
            msg.setDeleteFlag(1);
            msg.setIsRead(0);
            msg.setUpdateTime(new Date());
            messageCenterService.save(msg);
            logger.info("订单发货通知{}", JsonUtil.toJsonString(msg));

            Map<String, String> map = new HashMap<>();
            map.put("id", msg.getId() + "");
            jPushServiceImpl.pushAline(Arrays.asList(msg.getAccountEmail()), title, pushMsg, map);
        }
        return R.ok();
    }



    /**
     * 确认（拒绝）采购单
     */
    @PostMapping("/confirm")
    public R confirm(@RequestBody Map<String, Object> params) {
        R r = purchaseOrderService.updateStatus(params);
        return r;
    }

    /**
     * 确认（拒绝）采购单
     */
    @PostMapping("/ship")
    public R ship(@RequestBody Map<String, Object> params) {
        logger.info("提交经销商采购订单{}", JsonUtil.toJsonString(params));
        String orderId = StringUtil.obj2String(params.get("orderId"));
        String shipCompany = StringUtil.obj2String(params.get("shipCompany"));
        String shipNo = StringUtil.obj2String(params.get("shipNo"));

        PurchaseOrder order = purchaseOrderService.getOne(new QueryWrapper<PurchaseOrder>()
                .eq("id", Integer.parseInt(orderId)));

        SysUserEntity loginUser = HttpContextUtils.getLoginSysUserEntity();
        if (order.getDealerId().intValue() != loginUser.getUserId().intValue()){
            return R.error("无法操作他人采购单");
        }

        order.setStatus(3);
        order.setShipCompany(shipCompany);
        order.setShipNo(shipNo);
        order.setShipTime(new Date());
        purchaseOrderService.saveOrUpdate(order);

        Account account = accountService.getOne(new QueryWrapper<Account>()
                .eq("id", order.getAccountId()));

        //极光推送发货消息给用户
        String title = LanguageUtils.getValueByKey("ship.notice");
        String pushMsg = LanguageUtils.getValueByKey("ship.shipOrder") + ":" + order.getOrderNo() + ","
                + LanguageUtils.getValueByKey("ship.shipCompany") + ":" + order.getShipCompany() + ","
                + LanguageUtils.getValueByKey("ship.shipNo") + ":" + order.getShipNo() + ","
                + LanguageUtils.getValueByKey("ship.shipTime") + ":" + DateUtils.format(order.getShipTime(), DateUtils.DATE_TIME_PATTERN_V);

        MessageCenter msg = new MessageCenter();
        msg.setAccountEmail(account.getEmail());
        msg.setAccountId(account.getId());
        msg.setContent(pushMsg);
        msg.setTitle(title);
        msg.setCreateTime(new Date());
        SysUserEntity sysUserEntity = HttpContextUtils.getLoginSysUserEntity();
        msg.setCreatorId(sysUserEntity.getUserId());
        msg.setDeleteFlag(1);
        msg.setIsRead(0);
        msg.setUpdateTime(new Date());
        messageCenterService.save(msg);
        logger.info("订单发货通知{}", JsonUtil.toJsonString(msg));

        Map<String, String> map = new HashMap<>();
        map.put("id", msg.getId() + "");
        jPushServiceImpl.pushAline(Arrays.asList(msg.getAccountEmail()), title, pushMsg, map);

        return R.ok();
    }

}
